<template>
  <a-layout class="layout" :style="{height: `${height}px`}">
    <a-layout-sider class="side" breakpoint="lg" collapsedWidth="200" :width="350">
      <a-tree showIcon :loadData="onLoadData" :treeData="treeData" :selectedKeys="selectedKeys" :expandedKeys="expandedKeys" @select="onSelect"
        @expand="onExpand">
        <template slot="custom" slot-scope="{dataRef}">
          <a-icon :type="dataRef.icon" style="color: #1890ff;" @dblclick="onTreeNodeDbclick(dataRef.key)" />
        </template>
        <template slot="titleRender" slot-scope="{title, key}">
          <span @dblclick="onTreeNodeDbclick(key)" class="title">{{title}}</span>
        </template>
      </a-tree>
    </a-layout-sider>
    <a-layout-content class="content">
      <transition name="page-toggle" mode="out-in">
        <!-- <keep-alive :include="cacheList"> -->
        <keep-alive>
          <router-view ref="routerView" />
        </keep-alive>
      </transition>
    </a-layout-content>
  </a-layout>

</template>

<script>
import treeApi from '@/api/tree';

export default {
  name: 'baseTreeView',
  props: {
    treeUrl: {
      type: String,
      required: true
    },
    flag: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      height: 300,
      selectedKeys: [],
      expandedKeys: [],
      treeData: [],
      timer: null,
      // 是否处于显示状态
      isActive: false
    };
  },

  computed: {
    tagNavList() {
      return this.$store.state.app.tagNavList;
    },
    cacheList() {
      const list = [...(this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : [])];
      return list;
    },
    globalExpandKeys() {
      return this.$store.state.treeExpand.value;
    }
  },

  watch: {
    expandedKeys(newValue) {
      if (this.isActive) {
        this.$store.dispatch('treeExpand/setData', { data: newValue });
      }
    },
    globalExpandKeys(newValue) {
      if (!this.isActive) {
        this.expandedKeys = newValue;
      }
    }
  },

  created() {},

  mounted() {
    this.resizeHeight();
    this.treeLoad();
    this.$bus.on(this.$constant.BUS_EVENT.RESIZE, item => {
      this.resizeHeight();
    });
  },

  activated() {
    this.isActive = true;
  },
  deactivated() {
    this.isActive = false;
  },

  methods: {
    resizeHeight() {
      // 65 为 header，6 为 padding-top
      let tagHeight = this.$store.state.setting.multipage ? 40 : 0;
      this.height = window.innerHeight - tagHeight - 64 - 6;
    },
    treeLoad() {
      treeApi.loadTreeByRoot(this.treeUrl).then(res => {
        this.treeData = this.insertIcon(res.data);
        // 默认选中第一个，并且展开第一个节点
        if (!this.globalExpandKeys || this.globalExpandKeys.length <= 0) {
          this.$nextTick(() => {
            this.selectedKeys = [res.data[0].key];
            this.doOnselect(this.treeData[0]);
            this.expandedKeys = [res.data[0].key];
          });
        } else {
          this.expandedKeys = this.globalExpandKeys;
        }
      });
    },
    onLoadData(treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve();
          return;
        }
        let data = treeNode.dataRef;
        let params = { id: data.id, level: data.clz };
        treeApi.loadTreeByParent(this.treeUrl, params).then(res => {
          treeNode.dataRef.children = this.insertIcon(res.data);
          this.treeData = [...this.treeData];
          resolve();
        });
      });
    },
    /**
     * 树点击后，干三件事，
     * 1、修改store缓存
     * 2、发布总线点击事件
     * 3、通知当前routerView的view层刷新
     */
    onSelect(selectKey, event) {
      if (this.timer) {
        window.clearTimeout(this.timer);
        this.timer = null;
      }
      this.timer = window.setTimeout(() => {
        let treeNode = event.node.dataRef;
        this.selectedKeys = [treeNode.key];
        this.doOnselect(treeNode);
      }, 200);
    },
    /** 双击展开 */
    onTreeNodeDbclick(key) {
      if (this.timer) {
        window.clearTimeout(this.timer);
        this.timer = null;
      }

      if (this.expandedKeys.includes(key)) {
        let index = this.expandedKeys.findIndex(v => v === key);
        this.expandedKeys.splice(index, 1);
      } else {
        this.expandedKeys.push(key);
      }
    },
    /** 点击展开图标时的事件调用方法 */
    onExpand(expandedKeys, e) {
      this.expandedKeys = expandedKeys;
    },
    doOnselect(treeNode) {
      this.$store.dispatch('treeSelect/setData', { data: treeNode });
      this.$nextTick(() => {
        // 发布总线 - 树选择
        this.$bus.emit(this.$constant.BUS_EVENT.TREE_SELECT, treeNode);
        let view = this.$refs.routerView;
        view.onTreeSelect && view.onTreeSelect(treeNode);
      });
    },
    insertIcon(treeNodes) {
      return treeNodes.map(x => {
        x.scopedSlots = { icon: 'custom', title: 'titleRender' };
        return x;
      });
    }
  }
};
</script>

<style lang="less" scoped>
.layout {
  padding: 6px 0px 0px 8px;
  .side {
    margin-right: 8px;
    background: #fff;
    padding: 6px;
    overflow: auto;

    border: 1px solid #e8e8e8;
    padding: 2px 8px;
    border-radius: 2px;
    -moz-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 老的 Firefox */
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    &::-webkit-scrollbar {
      width: 8px;
      height: 12px;
      background-color: #f5f5f5;
      cursor: pointer;
    }
    &::-webkit-scrollbar-track {
      -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
      border-radius: 10px;
      background-color: #f5f5f5;
      cursor: pointer;
    }
    &::-webkit-scrollbar-thumb {
      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
      background-color: #e4e7ed;
      cursor: pointer;
    }
    &::-webkit-scrollbar-thumb:hover {
      background-color: #c0c4cc;
      cursor: pointer;
    }
  }
  .content {
    height: 100%;
    overflow: auto;
  }
}

.title {
  display: inline-block;
  width: calc(100% - 20px);
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
</style>
